<?php


namespace app\command;

use app\admin\model\vip\Code;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\console\Command;

class Export extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('export');
        // 设置参数
        $this->setDescription('数据统计')->setHelp("php think export");
    }


    public function export(): void
    {

        $list = (new Code())->select();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue([1, 1], 'ID');
        $sheet->setCellValue([2, 1], '用户名');
        $sheet->setCellValue([3, 1], '会员卡');
        $sheet->setCellValue([4, 1], '卡号');
        $sheet->setCellValue([5, 1], '卡密');
        $sheet->setCellValue([6, 1], '状态');
        $sheet->setCellValue([7, 1], '最后使用时间');
        $sheet->setCellValue([8, 1], '创建时间');


        $sheet->getColumnDimension('A')->setWidth(20);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('C')->setWidth(20);
        $sheet->getColumnDimension('D')->setWidth(20);
        $sheet->getColumnDimension('E')->setWidth(20);
        $sheet->getColumnDimension('F')->setWidth(20);
        $sheet->getColumnDimension('G')->setWidth(20);
        $sheet->getColumnDimension('H')->setWidth(20);


        $h = 2;
        foreach ($list as $v) {
            $status_text = $v['status'] == 0?"未使用":'已使用';
            $sheet->setCellValue([1, $h], $v['id']);
            $sheet->setCellValue([2, $h], $v['admin']['nickname']);
            $sheet->setCellValue([3, $h], $v['vipCard']['name']);
            $sheet->setCellValue([4, $h], $v['number']);
            $sheet->setCellValue([5, $h], $v['password']);
            $sheet->setCellValue([6, $h], $status_text);
            $sheet->setCellValue([7, $h], date('Y-m-d/m/y H:i:s',$v['user_expire_time']));
            $sheet->setCellValue([8, $h], date('Y-m-d/m/y H:i:s',$v['create_time']));

            $sheet->getStyle('C' . $h)->getAlignment()->setWrapText(true);

            $h++;
        }

        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $file = time() . '.xlsx';
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Access-Control-Expose-Headers:Content-Disposition');
        header('Content-Disposition: attachment;filename=' . $file);
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
    }

}
